package com.heraleign.http;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.util.HashMap;
import java.util.Map;

public class HttpInterface {
    public static void main(String[] args) {
        String url="http://172.16.84.236:8882/HJA-DICT/lcdp-app/server/app/orchestration/run/871588000464523264/testExecProc/1.0";
        Map headsMap = new HashMap();
        headsMap.put("LCDP-CSRF-TOKEN","AuditSendMessage");
        headsMap.put("LCDP- SIGNATURE","yMWNK1HQZ71jMSielT");
        String json= "{}";

        httpPostWithJsonAndHeader(url,json,headsMap);
    }
    public static String httpPostWithJsonAndHeader(String url, String json, Map<String, String> headsMap) {

        String result = "";

        HttpPost httpPost = new HttpPost(url);
        StringEntity entity = new StringEntity(json, "utf-8");
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        //头
        if (headsMap != null && !headsMap.isEmpty()) {
            headsMap.forEach((key, value) -> {
                httpPost.addHeader(key, value);
            });
        }
        try (CloseableHttpClient httpClient = HttpClients.createDefault();
             CloseableHttpResponse response = httpClient.execute(httpPost)) {

            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                //log.info("HTTP请求成功!");

                // 从响应模型中获取响应实体
                HttpEntity responseEntity = response.getEntity();
                if (responseEntity != null) {
                    result = EntityUtils.toString(responseEntity);
                }

            } else {
                //log.info("HTTP请求失败!");
                return null;
            }

           // log.info("返回结果:{}", result);
            return result;
        } catch (Exception e) {
           // log.error("HTTP请求出现异常4：", e);
            return null;
        }
    }
}
